//
//  NSNetwork.m
//  erhuo
//
//  Created by Jingru Nie on 14/12/30.
//  Copyright (c) 2014年 集易（北京）科技有限公司. All rights reserved.
//

#import "NSNetwork.h"
#import "NSHash.h"

@interface NSNetwork()
{
    NSMutableURLRequest *request;
}
@end

@implementation NSNetwork

- (id)init {
    return [self initWithURL:nil withMethod:_NETWORK_METHOD_GET_ withData:nil withType:_NETWORK_DATA_TYPE_TEXT_];
}

- (NSNetwork *)initWithURL:(NSURL *)url
                withMethod:(_NETWORK_METHOD_)method
                  withData:(NSDictionary *)data
                  withType:(_NETWORK_DATA_TYPE_)type
{
    self = [super init];
    request = [NSMutableURLRequest requestWithURL:url];
    if (method) {
        switch (method) {
            case _NETWORK_METHOD_POST_:
                [request setHTTPMethod:@"POST"];
                break;
                
            default:
                [request setHTTPMethod:@"GET"];
                break;
        }
        
    }
    if (method - 1) {
        NSData *body;
        if (type) {
            body = [self keyPair:data withType:type];
            //NSLog(@"%@",[[NSString alloc] initWithData:body  encoding:NSUTF8StringEncoding]);
        }else {
            if ([NSJSONSerialization isValidJSONObject:data]) {
                body = [NSJSONSerialization dataWithJSONObject:data options:NSJSONWritingPrettyPrinted error:nil];
            }
        }
        [request setHTTPBody:body];
        //NSLog(@"%@",[[NSString alloc] initWithData:body encoding:NSUTF8StringEncoding]);
    }
    return self;
}

- (NSNetwork *)initWithURL:(NSURL *)url
                withMethod:(_NETWORK_METHOD_)method
{
    return [self initWithURL:url withMethod:method withData:nil withType:_NETWORK_DATA_TYPE_TEXT_];
}

- (void)setURL:(NSURL *)url {
    [request setURL:url];
}

- (void)setMethod:(NSString *)method {
    if ([method length]) {
        [request setHTTPMethod:method];
    }
}

- (void)setData:(NSDictionary *)data
       withType:(_NETWORK_DATA_TYPE_)type
{
    NSData *body;
    if (type) {
        body = [self keyPair:data withType:type];
    }else {
        if ([NSJSONSerialization isValidJSONObject:data]) {
            body = [NSJSONSerialization dataWithJSONObject:data options:NSJSONWritingPrettyPrinted error:nil];
        }
    }
    [request setHTTPBody:body];
}

- (void)setData:(NSData *)data {
    [request setHTTPBody:data];
}

- (void)setCachePolicy:(NSURLRequestCachePolicy)policy
{
    [request setCachePolicy:policy];
}

- (void)setTimeoutInterval:(NSTimeInterval)timeinterval
{
    [request setTimeoutInterval:timeinterval];
}

- (void)setCookies:(NSHTTPCookie *)cookies {
    
}

- (NSString *)topStringWithMimeType:(NSString *)mimeType keyName:(NSString *)keyname fileName:(NSString *)filename boundary:(NSString *)bounds;
{
    NSMutableString *top = [NSMutableString string];
    [top appendFormat:@"--%@\r\n", bounds];
    if ([filename length]) {
        filename = [NSString stringWithFormat:@"; filename=\"%@\"", filename];
    }
    [top appendFormat:@"Content-Disposition: form-data; name=\"%@\"%@\r\n", keyname, filename];
    if ([filename length] && [mimeType length]) {
        [top appendFormat:@"Content-Type: %@\r\n", mimeType];
    }
    [top appendFormat:@"\r\n"];
    return top;
}

- (NSString *)bottomStringWithBoundary:(NSString *)bounds
{
    return [NSString stringWithFormat:@"--%@--\r\n", bounds];
}


- (NSData *)keyPair:(NSDictionary *)data
           withType:(_NETWORK_DATA_TYPE_)type
{
    NSString *bound = [@"----ErhuoAppBoundary" stringByAppendingString:[NSHash RandomString:20]];
    NSEnumerator *enume = [data keyEnumerator];
    NSMutableData *resultdata = [NSMutableData data];
    int test = 0;
    for (NSString *key in enume) {
        NSMutableString *filename = [NSMutableString stringWithFormat:@""];
        NSString *mimeType = nil;
        id filedata = [data objectForKey:key];
        if ([filedata isKindOfClass:[NSData class]]) {
            filename = [NSMutableString stringWithFormat:@"%d.",test];
            switch (type) {
                case _NETWORK_DATA_TYPE_PNG_:
                    mimeType = @"image/png";
                    [filename appendString:@"png"];
                    break;
                    
                default:
                    break;
            }
        }else {
            if (![filedata isKindOfClass:[NSString class]]) {
                continue;
            }
            filedata = [filedata dataUsingEncoding:NSUTF8StringEncoding];
        }
        NSString *top = [self topStringWithMimeType:mimeType keyName:key fileName:filename boundary:bound];
        [resultdata appendData:[top dataUsingEncoding:NSUTF8StringEncoding]];
        [resultdata appendData:filedata];
        [resultdata appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    }
    [resultdata appendData:[[self bottomStringWithBoundary:bound] dataUsingEncoding:NSUTF8StringEncoding]];
    
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",bound];
    [request setValue:contentType forHTTPHeaderField: @"Content-Type"];
    NSString *contentLength = [NSString stringWithFormat:@"%lu", (unsigned long)[resultdata length]];
    [request setValue:contentLength forHTTPHeaderField:@"Content-Length"];
    
    return resultdata;
}

- (void)sendRequest:(_NETWORK_RESPONSE_FINISH_)finishied {
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:finishied];
}

@end